package com.hiyee.article.controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

@Controller
@RequestMapping("freemarker")
public class FreemarkerController {

    final static Logger logger = LoggerFactory.getLogger(FreemarkerController.class);

    @Value("${freemarker.html.target}")
    private String target;

    @RequestMapping("/createHtml")
    public String createHtml(Model model) throws Exception{
        // 0、配置 freemarker 基本环境
        Configuration configuration = new Configuration(Configuration.getVersion());
        // 声明 freemarker 模板所需要加载的目录
        String classpath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath + "templates"));

        System.out.println(target);
        System.out.println(classpath);

        // 1、 获取现有ftl文件
        Template template = configuration.getTemplate("stu.ftl", "utf-8");

        // 2、获取动态数据
        String name = "hiyee.shop";
        model.addAttribute("name", name);

        // 3、融合动态数据和ftl
        File file = new File(target);
        if(!file.exists()) {
            file.mkdirs();
        }

        Writer out = new FileWriter(target + File.separator + "211121.html");
        template.process(model, out);
        out.close();

        return "ok";
    }

    @GetMapping("/hello")
    public Object hello(Model model) {

        // 输出字符串
        String name = "hiyee.shop";

        model.addAttribute("name", name);

        // 返回模板文件名称
        return "stu";
    }
}
